package sort.leetcode;

public class ReversePairs {
    public static int reversePairs(int[] nums) {
        // 使用归并排序
        return mergeSort(nums, 0, nums.length - 1);
    }

    private static int mergeSort(int[] nums, int left, int right) {
        if (right - left < 1) {
            return 0;
        }
        int sum = 0;
        int mid = left + ((right - left) >> 1);
        sum += mergeSort(nums, left, mid); // [left,mid]
        sum += mergeSort(nums, mid + 1, right); // [mid + 1, right]
        sum += merge(nums, left, mid, right);
        return sum;
    }

    private static int merge(int[] nums, int left, int mid, int right) {
        int count = 0;
        int[] copy = new int[right - left + 1];
        for (int i = left; i <= right; i++) {
            copy[i - left] = nums[i];
        }
        int index1 = left, index2 = mid + 1;
        for (int i = left; i <= right; i++) {
            if (index1 > mid) {
                nums[i] = copy[index2 - left];
                index2 ++;
            } else if (index2 > right) {
                nums[i] = copy[index1 - left];
                index1 ++;
            } else if (copy[index1 - left] <= copy[index2 - left]) {
                nums[i] = copy[index1 - left];
                index1 ++;
            } else {
                count += mid - index1 + 1;
                nums[i] = copy[index2 - left];
                index2 ++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] nums = new int[] {7, 5, 6, 4, 3, 2};
        System.out.println(reversePairs(nums));
    }
}
